################################################################################
### Technological Change and the International System Replication Files
### Figure 2. System Concentration and Interstate Conflict, 1816-2008
###  
### Required data files: "tech_data.dta"
###                    
### Created by: Thomas Cunningham
### Date: 27 January 2021
##################################################################


# Start from Clean Work Space
rm(list = ls())

# Set Working Directory
setwd(dirname(rstudioapi::getActiveDocumentContext()$path)) 
# Note: if you are not using R Studio this command will not work, set WD to source file location manually
require(readstata13)
require(ggplot2)
data <- read.dta13("tech_data.dta")

systemic <- data[!duplicated(data$year) & !is.na(data$sysconall), ]


systemic$ww_mids <- systemic$ww_mid

# Stacked:
syscon <- systemic[, c("year", "sysconall")]
syscon$type <- "syscon"
c4 <- systemic[, c("year", "c4")]
c4$type <- "c4"
viable <- systemic[, c("year", "nviable")]
viable$type <- "viable"
ww_mids <- systemic[, c("year", "ww_mids")]
ww_mids$type <- "ww_mids"
ww_war <- systemic[, c("year", "ww_war")]
ww_war$type <- "ww_war"
ww_delta <- systemic[, c("year", "ww_delta")]
ww_delta$type <- "ww_delta"

library(data.table)
stack <- rbindlist(list(syscon,
                        c4,
                        viable,
                        ww_mids,
                        ww_war,
                        ww_delta))

colnames(stack) <- c("year", "freq", "type")

stack$type[stack$type == "ww_mids"] <- "MIDs, worldwide"
stack$type[stack$type == "ww_war"] <- "Wars, worldwide"
stack <- stack[stack$year %in% 1816:2009, ]

B <- ggplot(stack, aes(x=year, y=freq))+
  geom_bar(data = stack[stack$type %in% c("Wars, worldwide", "MIDs, worldwide"), ], stat="identity", aes(fill = type))+
  theme_minimal()+
  theme(axis.title = element_blank(), legend.title = element_blank(), legend.position = "bottom")+
  guides(fill = guide_legend(reverse = TRUE))+ylab("")+
  scale_color_manual(values=c("black", "#E69F00", "#56B4E9"))

# Changing to grayscale for publication
(B = B + scale_fill_grey(start = .2, end = .7))

A <- ggplot(stack, aes(x=year, y=freq))+
  geom_line(data = stack[stack$type == "syscon", ], aes(y=freq, x = year), alpha = 1,  col = "black")+
  theme_minimal()+xlab("")+
  theme(legend.title = element_blank(),
        axis.title = element_blank(),
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+ylab("")

library(gridExtra)

gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
grid::grid.newpage()
grid::grid.draw(rbind(gA, gB))
ggsave("output/figure2.pdf", width = 8, height = 4, grid::grid.draw(rbind(gA, gB)))
